package com.example.fashionshoes.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fashionshoes.constant.JwtConst;
import com.example.fashionshoes.exception.BusinessException;
import com.example.fashionshoes.mapper.AddressBookMapper;
import com.example.fashionshoes.pojo.po.AddressBook;
import com.example.fashionshoes.service.AddressBookService;
import com.example.fashionshoes.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    /**
     * 新增地址簿
     *
     * @param addressBook 地址簿
     * @return 更新结果
     */
    @Override
    public Boolean insert(AddressBook addressBook) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        //是否为第一个地址
        List<AddressBook> addressBookList = lambdaQuery().eq(AddressBook::getUserId, userId).list();
        if (addressBookList.isEmpty()) {
            addressBook.setIsDefault(0);
        }
        addressBook.setUserId(userId);
        addressBook.setFullAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        try {
            return save(addressBook);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取地址簿信息
     *
     * @return 地址簿信息
     */
    @Override
    public List<AddressBook> getAddress() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        return lambdaQuery().eq(AddressBook::getUserId, userId).list();
    }

    /**
     * 修改默认收货地址
     */
    @Override
    public void updateDefaultAddress(Integer addressId) throws BusinessException {
        if (addressId == null) {
            throw new BusinessException("修改失败！");
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        //将所有地址修改为非默认
        lambdaUpdate().eq(AddressBook::getUserId, userId).set(AddressBook::getIsDefault, 1).update();
        lambdaUpdate().eq(AddressBook::getId, addressId).eq(AddressBook::getUserId, userId).set(AddressBook::getIsDefault, 0).update();
    }
}
